package com.scs.application.modules.wm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.base.entity.Dept;
import com.scs.application.modules.base.service.DeptService;
import com.scs.application.modules.wm.entity.StockSafety;
import com.scs.application.modules.wm.mapper.StockSafetyMapper;
import com.scs.application.modules.wm.service.StockSafetyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 */
@Service
public class StockSafetyServiceImpl extends BaseServiceImpl<StockSafetyMapper, StockSafety> implements StockSafetyService {

    @Autowired
    private DeptService deptService;

    @Override
    public boolean saveOrUpdate(StockSafety stockSafety) {
        if (StringUtils.isBlank(stockSafety.getId())){
            int count = baseMapper.selectCount(new QueryWrapper<StockSafety>()
                    .eq("matr_id", stockSafety.getMatrId())
                    .eq("warehouse_id", stockSafety.getWarehouseId())
            );

            if (count > 0) {
                throw new BusinessException(String.format("'%s'在'%s'中已经维护过安全库存，不能重复维护", stockSafety.getMatrName(), stockSafety.getWarehouseName()));
            }
        }

        List<Dept> depts = deptService.list(Wrappers.<Dept>query().eq("warehouse_id", stockSafety.getWarehouseId()));
        if (depts == null || depts.isEmpty()) {
            throw new BusinessException(String.format("库存地'%s'没有对应的二级库科室，请先到科室里面设置", stockSafety.getWarehouseName()));
        }
        return super.saveOrUpdate(stockSafety);
    }
}
